package com.jz.community.modulemine.utils;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.jz.community.modulemine.R;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;


/**
 * Created by shequren on 2016/7/16.
 */
public class DownloadAppManager {
    private Context mContext;
    private Dialog mDownloadDialog;
    private ProgressBar mProgressBar;
    private boolean mCancelUpdate;
    private String mSavePath = "";
    private int mProgress;

    private static final int DOWNLOAD = 1;
    private static final int DOWNLOAD_FINISH = 2;

    private String file_name = "shequren.apk";
    private String urlDownload;

    public DownloadAppManager(Context mContext, String file_name, String url) {
        this.mContext = mContext;
        this.file_name = file_name;
        this.urlDownload = url;
    }
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case DOWNLOAD:
                    mProgressBar.setProgress(mProgress);
                    break;
                case DOWNLOAD_FINISH:
                    openFile(mSavePath);
                    break;
                default:
                    break;
            }
        };
    };

    public void showDownloadDialog() {
        mDownloadDialog = new Dialog(mContext, R.style.commonDialog);
        mDownloadDialog.setCancelable(false);
        final LayoutInflater inflater = LayoutInflater.from(mContext);
        View v = inflater.inflate(R.layout.module_mine_softupdate_progress, null);
        TextView txCancle = (TextView) v.findViewById(R.id.tx_cancle);
        txCancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mCancelUpdate = true;
                mDownloadDialog.dismiss();
            }
        });
        mProgressBar = (ProgressBar) v.findViewById(R.id.update_progress);
        mDownloadDialog.setContentView(v);
        mDownloadDialog.show();
        downloadApk();
    }

    private void downloadApk() {
        new downloadApkThread().start();
    }

    private class downloadApkThread extends Thread {
        @Override
        public void run() {
            try {
                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                    String sdpath = Environment.getExternalStorageDirectory() + "/";
                    mSavePath = sdpath + "download";
                    URL url = new URL(urlDownload);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.connect();
                    int length = conn.getContentLength();
                    InputStream is = conn.getInputStream();

                    File file = new File(mSavePath);
                    if (!file.exists()){
                        file.mkdir();
                    }
                    File apkFile = new File(mSavePath, file_name);
                    FileOutputStream fos = new FileOutputStream(apkFile);
                    int count = 0;
                    byte buf[] = new byte[1024];
                    do {
                        int numread = is.read(buf);
                        count += numread;
                        mProgress = (int) (((float) count / length) * 100);
                        mHandler.sendEmptyMessage(DOWNLOAD);
                        if (numread <= 0) {
                            mHandler.sendEmptyMessage(DOWNLOAD_FINISH);
                            break;
                        }
                        fos.write(buf, 0, numread);
                    } while (!mCancelUpdate);
                    fos.close();
                    is.close();
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            mDownloadDialog.dismiss();
        }
    }

    /**
     * 安装 文件（APK）
     */
    private void openFile(String apk) {
        Intent intents = new Intent();
        intents.setAction(Intent.ACTION_VIEW);
        intents.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intents.setDataAndType(Uri.fromFile(new File(apk, file_name)), "application/vnd.android.package-archive");
        mContext.startActivity(intents);
    }
}
